package com.changgou.order.listener;

import com.changgou.entity.Constants;
import com.changgou.order.dao.OrderConfigMapper;
import com.changgou.order.dao.OrderMapper;
import com.changgou.order.pojo.Order;
import com.changgou.order.pojo.OrderConfig;
import com.changgou.order.service.OrderService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * 指定订单自动收货监听器
 */
@Component
@RabbitListener(queues = "order_tack")
public class OrderAutoTackListener {

    @Autowired
    private OrderConfigMapper orderConfigMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderService orderService;

    @RabbitHandler
    public void messageHandler(String msg) {
        //1. 获取order_config表中, 订单从下单开始多久算超时数据, 简称超时时间
        OrderConfig orderConfig = orderConfigMapper.selectByPrimaryKey("1");
        //获取超时时间
        Integer takeTimeout = orderConfig.getTakeTimeout();

        //2. 获取当前日期时间
        LocalDate localDate = LocalDate.now();


        //3. 当前时间-超时时间=具体的超时日期
        LocalDate timeOutDate = localDate.plusDays(-takeTimeout);

        //4. 从数据库中查询到在具体超时日期之间的订单数据
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        //付款时间小于等于超时日期的
        criteria.andLessThanOrEqualTo("payTime", timeOutDate);
        //发货状态为1已发货的
        criteria.andEqualTo("consignStatus", "1");
        //订单状态为, 未完成的
        criteria.andNotEqualTo("orderStatus", Constants.ORDER_STATUS_6);

        List<Order> orders = orderMapper.selectByExample(example);

        //5. 将查询到的订单数据执行收货
        if (orders != null && orders.size() > 0) {
            for (Order order : orders) {
                orderService.take(order.getId(), "system");
            }
        }

    }
}
